<template>
  <div class="user-management-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理平台所有用户账户，包括审核、启用/禁用账户等操作</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="filter-card">
      <el-form
        :inline="true"
        :model="searchForm"
        class="filter-form"
      >
        <el-form-item label="用户名/邮箱">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入用户名或邮箱"
            class="search-input"
          />
        </el-form-item>

        <el-form-item label="角色">
          <el-select
            v-model="searchForm.role"
            placeholder="请选择角色"
            class="filter-select"
          >
            <el-option label="全部" value="" />
            <el-option label="企业" value="enterprise" />
            <el-option label="导师" value="tutor" />
            <el-option label="学生" value="student" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="filter-select"
          >
            <el-option label="全部" value="" />
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已暂停" value="suspended" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="userList"
          border
          stripe
          :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': '500' }"
          class="user-table"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />

          <el-table-column prop="username" label="用户名" min-width="120">
            <template #default="scope">
              <div class="user-info">
                <el-avatar
                  :src="scope.row.avatar"
                  size="small"
                  class="user-avatar"
                  v-if="scope.row.avatar"
                />
                <span class="username">{{ scope.row.username }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="real_name" label="真实姓名" min-width="100" />
          <el-table-column prop="email" label="邮箱" min-width="180" />
          <el-table-column prop="phone" label="手机号" min-width="120" />

          <el-table-column prop="role" label="角色" min-width="100">
            <template #default="scope">
              <el-tag
                :type="roleTypeMap[scope.row.role as keyof typeof roleTypeMap]?.type"
                size="small"
              >
                {{ roleTypeMap[scope.row.role as keyof typeof roleTypeMap]?.label || '未知角色'}}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              <el-tag
                :type="statusTypeMap[scope.row.status as keyof typeof statusTypeMap]?.type"  
                size="small"
              >
                {{ statusTypeMap[scope.row.status as keyof typeof statusTypeMap]?.label || '未知状态' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="CreatedAt" label="创建时间" min-width="160">
            <template #default="scope">
              {{ formatDate(scope.row.CreatedAt) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="140" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="text"
                @click="handleView(scope.row)"
                class="operation-btn"
              >
                查看
              </el-button>

              <el-button
                size="small"
                type="text"
                :disabled="scope.row.status === 'approved'"
                :class="scope.row.status === 'pending' ? 'text-primary' : 'text-success'"
                @click="handleUpdateStatus(scope.row, 'approved')"
                class="operation-btn"
              >
                {{ scope.row.status === 'pending' ? '审核通过' : '重新激活' }}
              </el-button>

              <el-button
                size="small"
                type="text"
                :disabled="scope.row.status === 'suspended' || scope.row.status === 'rejected'"
                class="text-danger operation-btn"
                @click="handleUpdateStatus(scope.row, 'suspended')"
              >
                暂停
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { userApi } from '@/api/admin.ts';
import type { User } from '@/api/adminTypes.ts';
type statusType =  'pending' | 'active' | 'inactive';
type roleType = 'enterprise' | 'teacher' | 'student' | 'admin';
// 角色类型映射
const roleTypeMap = {
  'enterprise': { label: '企业', type: 'primary' },
  'tutor': { label: '导师', type: 'success' },
  'student': { label: '学生', type: 'info' },
  'admin': { label: '管理员', type: 'warning' }
};

// 状态类型映射
const statusTypeMap = {
  'pending': { label: '待审核', type: 'warning' },
  'approved': { label: '已审核', type: 'success' },
  'rejected': { label: '已拒绝', type: 'danger' },
  'suspended': { label: '已暂停', type: 'info' }
};

// 搜索表单
const searchForm = reactive({
  keyword: '',
  role: '',
  status: ''
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 表格数据
const userList = ref<User[]>([]);
const loading = ref(false);
const statusLoading = ref<number | null>(null);

// 获取用户列表
const getUsers = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {
      page: pagination.page,
      size: pagination.size,
      role: searchForm.role || undefined,
      status: searchForm.status || undefined,
      keyword: searchForm.keyword || undefined
    };

    const res = await userApi.getUsers(params);
    userList.value = res.data;
    pagination.total = res.data.total || 0;
  } catch (error) {
    console.error('获取用户列表失败:', error);
     ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1; // 重置到第一页
  getUsers();
};

// 重置表单
const resetForm = () => {
  searchForm.keyword = '';
  searchForm.role = '';
  searchForm.status = '';
  pagination.page = 1;
  getUsers();
};

// 查看用户详情
const handleView = (row: User) => {
  // 这里可以跳转到用户详情页或打开详情弹窗
  console.log('查看用户:', row);
  ElMessage.info('用户详情功能待实现');
};

// 更新用户状态
const handleUpdateStatus = async (row: User, status: string) => {
  const statusLabelMap = {
    'approved': '审核通过',
    'suspended': '暂停',
    'rejected': '拒绝'
  };
  const statusLabel = statusLabelMap[status as keyof typeof statusLabelMap] || status;
  const confirmMessage = status === 'suspended'
    ? `确定要暂停用户【${row.username}】吗？暂停后该用户将无法登录系统。`
    : `确定要${statusLabel}用户【${row.username}】吗？`;

  try {
    // 确认操作
    const confirmResult = await ElMessageBox.confirm(
      confirmMessage,
      '操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmResult === 'confirm') {
      statusLoading.value = row.id;
      await userApi.updateUserStatus(row.id, status);
      ElMessage.success(`${statusLabel}成功`);
      getUsers(); // 重新获取列表
    }
  } catch (error) {
    if (error !== 'cancel') { // 如果不是用户取消操作
      console.error(`更新用户状态失败:`, error);
      ElMessage.error(`${statusLabel}失败，请重试`);
    }
  } finally {
    statusLoading.value = null;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  getUsers();
};

// 当前页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  getUsers();
};

// 定义时间格式化函数，明确参数和返回值类型
const formatDate = (dateString: string | undefined | null): string => {
  // 处理空值或undefined
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString);
    
    // 验证日期是否有效
    if (isNaN(date.getTime())) {
      return '无效时间';
    }
    
    // 获取年月日时分，并确保两位数格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('时间格式化失败:', error);
    return '格式化错误';
  }
};

// 如果需要，可以定义表格行数据的类型接口（根据实际数据结构调整）
interface TableRow {
  CreatedAt: string;
  // 其他字段...
  // id: number;
  // name: string;
}

// 初始化页面加载数据
getUsers();
</script>

<style scoped lang="scss">
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;

  h2 {
    margin-bottom: 5px;
    color: #1f2937;
  }

  p {
    color: #6b7280;
    font-size: 14px;
  }
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.filter-form {
  padding: 15px 0;

  .search-input {
    width: 200px;
  }

  .filter-select {
    width: 140px;
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.table-container {
  overflow-x: auto;
}

.user-table {
  width: 100%;

  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .user-avatar {
    background-color: #f0f2f5;
  }

  .operation-btn {
    margin: 0 5px;
  }
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

@media (max-width: 768px) {
  .filter-form {
    .el-form-item {
      margin-bottom: 10px;
      width: 100%;
    }

    .search-input, .filter-select {
      width: 100%;
    }
  }
}
</style>




